package com.xb.cloud.shopping.service;

import java.io.IOException;
import java.util.Date;
import java.util.Iterator;
import java.util.Map;
import java.util.TreeMap;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.alibaba.fastjson.JSON;
import com.xb.cloud.common.util.OKhttpsUtils;
import com.xb.cloud.common.util.SecurityDigestUtils;
import com.xb.cloud.shopping.model.PaymentConfig;

public class PaymentUtils {

	private static final Logger LOGGER = LoggerFactory.getLogger(PaymentUtils.class);

	/**
	 * 请求接口
	 * 
	 * @param postmap
	 * @return 响应字符串
	 * @throws IOException
	 */
	public static String handlePost(TreeMap<String, String> postmap, String interfaceName) throws IOException {
		String url = PaymentConfig.OPEN_URL + interfaceName;
		LOGGER.info("====请求地址= " + url);
		return OKhttpsUtils.doPost(url, postmap);
	}

	/**
	 * 签名
	 * 
	 * @param postmap
	 * @throws Exception
	 */
	public static TreeMap<String, String> handleSign(TreeMap<String, String> data, String openId, String openKey)
			throws Exception {
		TreeMap<String, String> postMap = new TreeMap<String, String>(); // 请求参数的map
		String timestamp = new Date().getTime() / 1000 + "";
		postMap.put("open_id", openId);
		postMap.put("open_key", openKey);
		postMap.put("timestamp", timestamp);

		// 1 data字段内容进行AES加密，再二进制转十六进制(bin2hex)
		String encryptData = SecurityDigestUtils.AESEncrypt(JSON.toJSONString(data), openKey); // AES加密，并bin2hex
		System.out.println("====加密后的data= " + encryptData);
		postMap.put("data", encryptData);

		// 2 请求参数签名 按A~z排序，串联成字符串，先进行sha1加密(小写)，再进行md5加密(小写)，得到签名
		String sign = sign(postMap);
		postMap.put("sign", sign);

		postMap.remove("open_key"); // 加密后移除
		return postMap;
	}

	/**
	 * 验签
	 * 
	 * @param respObject
	 * @return
	 */
	public static Boolean verifySign(Map<String, String> responseMap, String openKey) {
		String respSign = responseMap.get("sign");
		responseMap.remove("sign"); // 删除sign节点
		responseMap.put("open_key", openKey);
		System.out.println("==========开始验签==========");

		String veriSign = sign(responseMap); // 按A~z排序，串联成字符串，先进行sha1加密(小写)，再进行md5加密(小写)，得到签名
		if (respSign.equals(veriSign)) {
			System.out.println("==========验签成功==========");
			return true;
		}

		return false;
	}

	/**
	 * 签名
	 * 
	 * @param postMap
	 * @return
	 */
	public static String sign(Map<String, String> postMap) {
		String sign = null;
		try {
			String postParams = getPostParams(postMap);
			System.out.println("====排序后的待签名字符串= " + postParams);
			String sha1 = SecurityDigestUtils.SHA1(postParams);
			sign = SecurityDigestUtils.MD5(sha1);
		} catch (Exception e) {
			e.printStackTrace();
		}

		return sign;
	}

	public static String getPostParams(Map<String, String> paramMap) throws Exception {
		TreeMap<String, String> sortMap = new TreeMap<>();

		for (Iterator<String> it = paramMap.keySet().iterator(); it.hasNext();) {
			String key = (String) it.next();
			sortMap.put(key, paramMap.get(key));
		}

		String sort = "";
		for (Iterator<String> it = sortMap.keySet().iterator(); it.hasNext();) {
			String key = (String) it.next();
			sort = sort + key + "=" + sortMap.get(key).toString() + "&";
		}
		if ((sort != null) && (!("".equals(sort)))) {
			sort = sort.substring(0, sort.length() - 1);
		}
		return sort;
	}

}
